﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System.IO; 

namespace AzureFileDepot.Helpers
{

    public class AzureBlob
    {
        CloudStorageAccount storageAccount;
        CloudBlobClient blobClient;
        CloudBlobContainer blobContainer;

        public AzureBlob(string storageConnectionStr, string containerName)
        {
            storageAccount = CloudStorageAccount.Parse(storageConnectionStr);
            blobClient = storageAccount.CreateCloudBlobClient();
            blobContainer = blobClient.GetContainerReference(containerName);
        }

        /// <summary>
        /// This method generates a shared access signature for a single blob that's good for 1 hour.
        /// </summary>
        /// <param name="containerName">Container the blob is in</param>
        /// <param name="blobName">name of blob to create a signature for</param>
        /// <returns>the query string parameters of the signature</returns>
        public string CreateReadSaS(string containerName, string blobName)
        {
            SharedAccessBlobPolicy sasPolicy = new SharedAccessBlobPolicy()
            {
                // #DepotTip
                // we subtract 5 minutes from the start time to help prevent errors due to 
                // clock drift between the SaS issuer and consumer
                SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
                Permissions = SharedAccessBlobPermissions.Read
            };

            CloudBlockBlob fileBlob = blobContainer.GetBlockBlobReference(blobName);
            string accessSignature = fileBlob.GetSharedAccessSignature(sasPolicy);
            return fileBlob.Uri + accessSignature;
        }

        public void uploadFromStream(Stream file, string blobName)
        {
            CloudBlockBlob fileBlob = blobContainer.GetBlockBlobReference(blobName);
            fileBlob.UploadFromStream(file, null, null, null);
        }

        static public void downloadFromBlob(Uri URI, Stream saveFile)
        {
            CloudBlockBlob fileBlob = new CloudBlockBlob(URI);
            fileBlob.DownloadToStream(saveFile);
        }
    }
}
